package com.hong.order;

import com.hong.zoo.ZkDistributeImproveLock;
import com.hong.zoo.ZkDistributeLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OrderServiceWithLock {

    //private OrderCodeGenerator org = new OrderCodeGenerator();
    // 模拟OrderCodeGenerator为共享资源
    private static OrderCodeGenerator org = new OrderCodeGenerator();

    /**
     * 使用ReentrantLock,它只能锁住一个JVM进程内的共享资源,但分布式是跨JVM进程的
     */
   // private Lock lock = new ReentrantLock();

    /**
     * 使用分布式锁
     */
 //   private Lock lock = new ZkDistributeLock("/order_sequence");

    public void createOrder() {
        Lock lock = new ZkDistributeImproveLock("/order_sequence");
        String orderCode = null;
        try {
            lock.lock();
            orderCode = org.generateCode();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName() + "====>" + orderCode);
        //其他业务
    }
}
